<?php
class Pictures extends Model_Abstract
{
	public $tableName = 'pm_pictures';
	
	protected $_validation = array(
		'name' => array(
			array('max_length', '图片名称长度不能超过100', 100),
			array('not_empty', '请填写图片名称')
		),
		'filename' => array(
			array('max_length', '文件名不能超过100个字符', 100),
			array('not_empty', '文件名不能为空')
		),
		'size' => array(
			array('is_int', '请用数字表述文件大小，单位为Kbyte'),
			array('not_null', '请给出文件大小')
		),
		'albumid' => array(
			array('is_int', 'albumid不正确'),
			array('not_empty', '请选择相册')
		),
		'quality' => array(
			array('is_int', 'quality必须是数字')
		),
		'type' => array(
			array('in_array', '类型不合法，仅限local和grabed', array('local', 'grabed')),
		)
	);
	
	public function init()
	{
		$this->initAttributes();
	}
	
	public function initAttributes()
	{
		$this->attributes = array(
			'filename' =>'',
			'size' => 0,
			'albumid' => 0,
			'type' => '',
			'quality' => '',
			'hasThumbnail' => 0,
			'created_date' => '',
			'created_int' => ''
		);
	}
	
	public static function model($classname = __CLASS__)
	{
		return parent::model($classname);
	}
	
	public function attributeLabels()
	{
		return array(
			'name' => '图片名称'
		);
	}
	
	protected function _find($fields = '*', $attributes = array(), $constraint = array(), $conditions = array(), $params = array())
	{
		$result = parent::_find($fields, $attributes, $constraint, $conditions, $params);
		$c = array_merge(
			$this->_constraintFind,
			array('getFilePath' => false, 'getAlbumInfo' => false),
			$constraint
		);
		extract($c);
		
		if($getFilePath || $getAlbumInfo){
			$albumAllSimple = Albums::model()->find();
		}
		if($getFilePath){
			foreach($result as $k => $v){
				$albumFolder = Albums::model()->getFolderPath(array('id' => $v['albumid']), $albumAllSimple);
				$result[$k]['orifilePath'] = $albumFolder['sysPath'] . 'orignal/' . $v['filename'];
				$result[$k]['thumbnailFilePath'] = $albumFolder['sysPath'] . 'thumbnail/' . $v['filename'];
				$result[$k]['orifileSrc'] = $albumFolder['relativePath'] . 'orignal/' . $v['filename'];
				$result[$k]['thumbnailFileSrc'] = $albumFolder['relativePath'] . 'thumbnail/' . $v['filename'];
			}
		}
		
		if($getAlbumInfo){
			$result = $this->mergeAlbumWithId($this->setResultKey($albumAllSimple, 'id'), $result);
		}
		
		return $result;
	}
	
	protected function _delete($attributes = array(), $conditions = array(), $params = array())
	{
		$deletedItems = $this->find('*', $attributes, array(), $conditions, $params);
		$this->_before_sql();
		$this->_filterAttributesScriptTags();
		if(parent::_delete($attributes, $conditions, $params)){
			$albumAllSimple = Albums::model()->find();
			foreach($deletedItems as $k => $item){
				$albumFolder = Albums::model()->getFolderPath(array('id' => $item['albumid']), $albumAllSimple);
				@unlink($albumFolder['sysPath'] . 'orignal/' . $item['filename']);
	    		@unlink($albumFolder['sysPath'] . 'thumbnail/' . $item['filename']);
			}
			
			return true;
		}else{
			return false;
		}
	}
	
	protected static function getUploadifyFile()
	{
		if(!empty($_FILES['Filedata'])){
			return $_FILES['Filedata'];
		}
		
		return null;
	}
	
	protected function uploadingPhoto($albumId = null, $fileInfo, $quality)
    {
        list($usec, $sec) = explode(" ", microtime());
        
    	$orignalFile = '';
    	if(isset($fileInfo['tmp_name'])){
			$tempFile = $fileInfo['tmp_name'];
			$targetPath = Albums::model()->getFolderPath(array('id' => $albumId));
		    $fileType = Util::getFileType($tempFile);
		    if($fileType == 'Unknown'){
		    	$error = Util::getMessage('UPLOAD-IMG-TYPE-ERROR');
		    	return array(
		    		'result' => false,
					'error' => $error
		    	);
		    }
	
		    $fileName = $usec.'_'.$sec.'_'.$albumId.'_'.rand().$fileType;				//usec_sec_albumid.fileType
		   	
		    $originalPath = $targetPath['sysPath'] . '/orignal';
		    @mkdir($originalPath, 0777, true);
		    $orignalFile = $originalPath.'/'.$fileName;
		    $orignalFileSrc = $targetPath['relativePath'] . '/orignal/'.$fileName;
		    //move_uploaded_file($tempFile, $orignalFile);
		    copy($tempFile, $orignalFile);
    	}
	    
    	if(is_readable($orignalFile)){
	    	$image = new Image();
			$image->createFromFile($orignalFile);
			if($image->save($orignalFile, $quality)){
				$orignalFileSize = filesize($orignalFile);
				if($image->getWidth() > PIC_THUMBNAIL_WIDTH){
		    		$image->resize(PIC_THUMBNAIL_WIDTH, -1);
		    	}
		    	$thumbnailPath = $targetPath['sysPath'].'/thumbnail';
			    @mkdir($thumbnailPath, 0777, true);
		    	$thumbnailFile = $thumbnailPath.'/'.$fileName;
		    	$thumbnailFileSrc = $targetPath['relativePath'].'/thumbnail'.'/'.$fileName;
				if(!$image->save($thumbnailFile, $quality)){
					$error = Util::getMessage('SAVE-THUMBNAIL-PHOTO-ERROR');
				}				
			}
    	}else{
    		$error = Util::getMessage('SAVE-ORIGINAL-PHOTO-ERROR');
    	}
    	
		if(empty($error)){
			return array(
				'result' => true,
				'fileName' => $fileName,
				'orignalFile' => $orignalFile,
				'orignalFileSrc' => $orignalFileSrc,
				'orignalFileSize' => intval($orignalFileSize),
				'thumbnailFile' => $thumbnailFile,
				'thumbnailFileSrc' => $thumbnailFileSrc
			);
		}else{
			return array(
				'result' => false,
				'error' => $error
			);
		}
    }
	
    public function processUploadifyPhoto($albumId = null, $quality)
    {
    	$fileInfo = self::getUploadifyFile();
    	return $this->uploadingPhoto($albumId, $fileInfo, $quality);
    }
    
	public function mergeAlbumWithId($albums, $pics)
	{
		foreach($pics as $k => $pic){
			$pics[$k]['album_name'] = '';
			$pics[$k]['album_name_en'] = '';
			$pics[$k]['album_foldername'] = '';
			$pics[$k]['album_sketch'] = '';
		
			if(!empty($albums[$pic['albumid']])){
				$pics[$k]['album_name'] = $albums[$pic['albumid']]['name'];
				$pics[$k]['album_name_en'] = $albums[$pic['albumid']]['name_en'];
				$pics[$k]['album_foldername'] = $albums[$pic['albumid']]['foldername'];
				$pics[$k]['album_sketch'] = $albums[$pic['albumid']]['sketch'];
			}
		}
		return $pics;
	}
    
	public function getDefaultshows($num = PICS_DEFAULT_SHOWNUM)
	{
		$constraint = array(
			'getAlbumInfo' => true,
			'getFilePath' => true,
			'orderBy' => array(
				'fields' => array('created_int'),
				'seq' => array('DESC')
			),
			'limit' => $num
		);
		
		return $this->find('*', null, $constraint);
	}
}